<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import axios from "@/util/axios";
import { ElMessage } from "element-plus";

const tableData = ref([]);

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    Required: true,
  },
  detailsTitle: {
    type: String,
    default: null,
    Required: true,
  },
  detailsVisible:{
    type:Boolean,
    default:false,
    required:true
  }
});

const ruleForm = ref({
  id: -1,
  name: "",
  remark: "",
});

const rules = ref({
  name: [{ required: true, message: "请输入大类名称" }],
  remark: [{ required: true, message: "请输入描述" }],
});

const ruleFormRef = ref(null);

const initFormData = async (id) => {
  const res = await axios.get("admin/fruitType/" + id);

  ruleForm.value = res.data.fruitType;
};

watch(
  //里面有两个参数，第一个props监听哪个参数
  () => props.detailsVisible,
  //第二个监听后要执行的哪个操作
  () => {
    console.log("id=" + props.id);
    let id = props.id;
    if (id != -1) {
      initFormData(id);
    }else{
      ruleForm.value={
        id:-1,
        name:"",
        remark:""
      }
      
    }
  }
);

 // 定义父组件事件
 const emits=defineEmits(['update:modelValue','initBigTypeList','initFruitTypeList'])
 const handleClose=()=>{
 console.log("xxx")
 // 调用执行
emits('update:modelValue',false)
 }

const handleConfirm = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let result = await axios.post("admin/fruitType/save", ruleForm.value);
      let data = result.data;
      if (data.code == 0) {
        ElMessage.success("执行成功");
        ruleFormRef.value.resetFields();
        emits("initFruitTypeList")
        handleClose();
      } else {
        ElMessage.error(data.msg);
      }
    } else {
      console.log("fail");
      return false;
    }
  });
};
</script>

<template>
  <!-- Dialog 对话框实现详情按钮弹窗显示， 饿了么ui组件 -->
  <!-- model-value是否显示 Dialog -->
  <!-- title说明：Dialog 对话框 Dialog 的标题， 也可通过具名 slot （见下表）传入 -->
  <!-- detailsVisible是从父组件order下index传过来 -->
  <el-dialog model-value="detailsVisible" :title="detailsTitle" width="40%">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="大类名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>

      <el-form-item label="描述" prop="remark">
        <!-- textarea文本域   rows行数  -->
        <el-input v-model="ruleForm.remark" type="textarea" :rows="4" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button type="primary" @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>